import qs from 'qs'

export const state = () => ({
  token: null
})

export const mutations = {
  GET_TOKEN(state) {
    state.token = this.$cookies.get('token')
  },
  SET_TOKEN(state, token) {
    this.$cookies.set('token', token)
  }
}

const formData = qs.stringify({
  username: 'alice',
  password: 'secret',
  grant_type: 'password'
})

export const actions = {
  async nuxtServerInit(store, { $axios }) {
    try {
      // OAuth 2.0密码凭据授权
      const res = await $axios.post('/api/token', formData, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
      const token = res.data.access_token

      // 将token 添加到后续请求的headers中
      store.commit('SET_TOKEN', token)
      // $axios.setToken(token, 'Bearer')
    } catch (error) {
      console.error('Error at getting OAuth 2.0 token:', error)
      // throw error
    }
  }
}
